package net.flowas.genericcrud.audit.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import net.flowas.genericcrud.audit.TreeWrapper;

public class TreeUtil {
  private TreeUtil() {}
  /**
   * 根据parentId信息确定列表中元素的父子关系.
   * @param input 没有父子关系的元素列表
   * @return 转换为父子关系的元素列表
   */
  public static List<TreeWrapper> plainToTree(List<TreeWrapper> input) {
    List<TreeWrapper> result = new ArrayList<>();
    Map<String, TreeWrapper> treeCache = new HashMap<>();
    for (TreeWrapper treeWrapper : input) {
      if (treeWrapper.getChildren() != null && !treeWrapper.getChildren().isEmpty()) {
        throw new IllegalAccessError("列表已经具有父子关系");
      }
      treeCache.put(treeWrapper.getId(), treeWrapper);
      if (treeWrapper.getParentId() == null) {
        result.add(treeWrapper);
      }
    }
    for (TreeWrapper treeWrapper : input) {
      if (treeWrapper.getParentId() != null) {
        TreeWrapper parentNode = treeCache.get(treeWrapper.getParentId());
        if (parentNode != null) {
          List<TreeWrapper> children = parentNode.getChildren();
          if (children == null) {
            children = new ArrayList<>();
            parentNode.setChildren(children);
          }
          //treeWrapper.setParentName(parentNode.getText());
          children.add(treeWrapper);
        }
      }
    }
    return result;
  }
  public static List<TreeWrapper> treeToplain(List<TreeWrapper> input) {
    Map<String, TreeWrapper> treeCache = new HashMap<>();
    treeToplainInternal(input,treeCache);
    List<TreeWrapper> result=new ArrayList<>();
    for(TreeWrapper node: treeCache.values()){
      //TreeWrapper node = treeCache.get(key);
      node.setChildren(null);
      result.add(node);
    }
    return result;
  }
  
  public static void treeToplainInternal(List<TreeWrapper> input,Map<String, TreeWrapper> treeCache) {
    for (TreeWrapper treeWrapper : input) {
      treeCache.put(treeWrapper.getId(), treeWrapper);
      if(treeWrapper.getChildren()!=null && !treeWrapper.getChildren().isEmpty()){
         treeToplainInternal(treeWrapper.getChildren(), treeCache);
      }
    }
  }
}
